<template>
  <div class="case-filing-detail">
    <div class="container mx-auto px-4 py-6">
      <!-- 页面标题 -->
      <div class="mb-8">
        <div class="flex items-center justify-between">
          <div>
            <h1 class="text-2xl font-bold text-gray-800 mb-2">案件立案详情</h1>
            <p class="text-gray-600">案件编号：{{ caseNumber }}</p>
          </div>
          <div class="flex gap-3">
            <el-button @click="$router.go(-1)" icon="el-icon-back">
              返回
            </el-button>
            <el-button type="primary" @click="refreshData" :loading="loading">
              刷新
            </el-button>
          </div>
        </div>
      </div>

      <!-- 案件基本信息 -->
      <div class="bg-white rounded-lg shadow-md mb-6">
        <div class="p-6 border-b border-gray-200">
          <h2 class="text-lg font-semibold text-gray-800">案件基本信息</h2>
        </div>
        <div class="p-6">
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <div class="space-y-3">
              <div class="flex justify-between">
                <span class="text-gray-600">案件编号：</span>
                <span class="text-gray-800 font-medium">{{ caseInfo.caseNumber }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">案件标题：</span>
                <span class="text-gray-800 font-medium">{{ caseInfo.caseTitle }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">案件类型：</span>
                <span class="text-gray-800 font-medium">{{ caseInfo.caseType }}</span>
              </div>
            </div>
            <div class="space-y-3">
              <div class="flex justify-between">
                <span class="text-gray-600">当事人：</span>
                <span class="text-gray-800 font-medium">{{ caseInfo.clientName }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">联系电话：</span>
                <span class="text-gray-800 font-medium">{{ caseInfo.phone }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">接收日期：</span>
                <span class="text-gray-800 font-medium">{{ caseInfo.receivedDate }}</span>
              </div>
            </div>
            <div class="space-y-3">
              <div class="flex justify-between">
                <span class="text-gray-600">立案状态：</span>
                <el-tag :type="getFilingStatusType(caseInfo.filingStatus)">
                  {{ getFilingStatusText(caseInfo.filingStatus) }}
                </el-tag>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">材料完整性：</span>
                <div class="flex items-center">
                  <el-progress 
                    :percentage="caseInfo.materials" 
                    :color="getProgressColor(caseInfo.materials)"
                    :show-text="false"
                    style="width: 80px; margin-right: 8px;"
                  />
                  <span class="text-sm text-gray-600">{{ caseInfo.materials }}%</span>
                </div>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">立案号：</span>
                <span class="text-gray-800 font-medium">{{ caseInfo.trackingNumber || '未生成' }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 立案进度 -->
      <div class="bg-white rounded-lg shadow-md mb-6">
        <div class="p-6 border-b border-gray-200">
          <h2 class="text-lg font-semibold text-gray-800">立案进度</h2>
        </div>
        <div class="p-6">
          <el-steps :active="activeStep" finish-status="success" align-center>
            <el-step title="材料收集" description="收集案件相关材料" />
            <el-step title="材料审核" description="审核材料完整性" />
            <el-step title="生成文书" description="生成立案所需文书" />
            <el-step title="提交立案" description="提交立案申请" />
            <el-step title="立案完成" description="立案流程完成" />
          </el-steps>
        </div>
      </div>

      <!-- 材料清单 -->
      <div class="bg-white rounded-lg shadow-md mb-6">
        <div class="p-6 border-b border-gray-200">
          <div class="flex justify-between items-center">
            <h2 class="text-lg font-semibold text-gray-800">材料清单</h2>
            <el-button type="primary" size="small" @click="uploadMaterial">
              <i class="fas fa-upload mr-1"></i>
              上传材料
            </el-button>
          </div>
        </div>
        <div class="p-6">
          <el-table :data="materials" style="width: 100%">
            <el-table-column prop="name" label="材料名称" min-width="200" />
            <el-table-column prop="type" label="材料类型" width="120" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getMaterialStatusType(scope.row.status)">
                  {{ getMaterialStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="uploadTime" label="上传时间" width="180" />
            <el-table-column prop="size" label="文件大小" width="100" />
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button size="small" type="primary" @click="previewMaterial(scope.row)">
                  预览
                </el-button>
                <el-button size="small" type="success" @click="downloadMaterial(scope.row)">
                  下载
                </el-button>
                <el-button size="small" type="danger" @click="deleteMaterial(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 生成文书 -->
      <div class="bg-white rounded-lg shadow-md mb-6">
        <div class="p-6 border-b border-gray-200">
          <div class="flex justify-between items-center">
            <h2 class="text-lg font-semibold text-gray-800">生成文书</h2>
            <el-button type="primary" @click="generateAllDocuments" :loading="generating">
              <i class="fas fa-magic mr-1"></i>
              一键生成
            </el-button>
          </div>
        </div>
        <div class="p-6">
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <div 
              v-for="doc in documents" 
              :key="doc.id"
              class="border rounded-lg p-4 hover:shadow-md transition-shadow"
            >
              <div class="flex items-center justify-between mb-3">
                <div class="flex items-center">
                  <i :class="getDocumentIcon(doc.type)" class="text-blue-600 mr-2"></i>
                  <span class="font-medium text-gray-800">{{ doc.name }}</span>
                </div>
                <el-tag :type="doc.status === 'generated' ? 'success' : 'info'" size="small">
                  {{ doc.status === 'generated' ? '已生成' : '未生成' }}
                </el-tag>
              </div>
              <p class="text-sm text-gray-600 mb-3">{{ doc.description }}</p>
              <div class="flex gap-2">
                <el-button 
                  size="small" 
                  type="primary" 
                  @click="generateDocument(doc)"
                  :loading="doc.generating"
                  :disabled="doc.status === 'generated'"
                >
                  {{ doc.status === 'generated' ? '重新生成' : '生成' }}
                </el-button>
                <el-button 
                  size="small" 
                  type="success" 
                  @click="downloadDocument(doc)"
                  :disabled="doc.status !== 'generated'"
                >
                  下载
                </el-button>
                <el-button 
                  size="small" 
                  type="info" 
                  @click="previewDocument(doc)"
                  :disabled="doc.status !== 'generated'"
                >
                  预览
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 立案记录 -->
      <div class="bg-white rounded-lg shadow-md">
        <div class="p-6 border-b border-gray-200">
          <h2 class="text-lg font-semibold text-gray-800">立案记录</h2>
        </div>
        <div class="p-6">
          <el-timeline>
            <el-timeline-item
              v-for="record in filingRecords"
              :key="record.id"
              :timestamp="record.time"
              :type="getTimelineItemType(record.type)"
            >
              <div class="flex justify-between items-start">
                <div>
                  <h4 class="font-medium text-gray-800">{{ record.title }}</h4>
                  <p class="text-sm text-gray-600 mt-1">{{ record.description }}</p>
                </div>
                <el-tag :type="getRecordStatusType(record.status)" size="small">
                  {{ getRecordStatusText(record.status) }}
                </el-tag>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'CaseFilingDetail',
  setup() {
    const route = useRoute()
    const loading = ref(false)
    const generating = ref(false)
    
    // 案件信息
    const caseInfo = ref({
      caseNumber: 'CASE2024001',
      caseTitle: '交通事故人身损害赔偿纠纷',
      caseType: '民事纠纷',
      clientName: '王先生',
      phone: '138****8888',
      receivedDate: '2024-01-15',
      filingStatus: 'processing',
      materials: 85,
      trackingNumber: ''
    })

    // 立案进度
    const activeStep = ref(2)

    // 材料清单
    const materials = ref([
      {
        id: 1,
        name: '交通事故认定书',
        type: '证据材料',
        status: 'uploaded',
        uploadTime: '2024-01-15 10:30:00',
        size: '2.5MB'
      },
      {
        id: 2,
        name: '医疗费用清单',
        type: '证据材料',
        status: 'uploaded',
        uploadTime: '2024-01-15 11:20:00',
        size: '1.8MB'
      },
      {
        id: 3,
        name: '身份证复印件',
        type: '身份证明',
        status: 'uploaded',
        uploadTime: '2024-01-15 14:15:00',
        size: '0.5MB'
      },
      {
        id: 4,
        name: '授权委托书',
        type: '委托材料',
        status: 'missing',
        uploadTime: '',
        size: ''
      }
    ])

    // 生成文书
    const documents = ref([
      {
        id: 1,
        type: 'complaint',
        name: '民事起诉状',
        description: '根据案件信息自动生成的起诉状',
        status: 'generated',
        generating: false
      },
      {
        id: 2,
        type: 'evidenceList',
        name: '证据清单',
        description: '整理的所有证据材料清单',
        status: 'generated',
        generating: false
      },
      {
        id: 3,
        type: 'powerOfAttorney',
        name: '授权委托书',
        description: '当事人授权律师代理的委托书',
        status: 'pending',
        generating: false
      },
      {
        id: 4,
        type: 'identityDocuments',
        name: '身份证明',
        description: '当事人身份证明材料',
        status: 'pending',
        generating: false
      }
    ])

    // 立案记录
    const filingRecords = ref([
      {
        id: 1,
        time: '2024-01-15 10:30:00',
        type: 'upload',
        title: '上传交通事故认定书',
        description: '成功上传交通事故认定书材料',
        status: 'success'
      },
      {
        id: 2,
        time: '2024-01-15 11:20:00',
        type: 'upload',
        title: '上传医疗费用清单',
        description: '成功上传医疗费用清单材料',
        status: 'success'
      },
      {
        id: 3,
        time: '2024-01-15 14:15:00',
        type: 'upload',
        title: '上传身份证复印件',
        description: '成功上传当事人身份证复印件',
        status: 'success'
      },
      {
        id: 4,
        time: '2024-01-15 16:00:00',
        type: 'generate',
        title: '生成民事起诉状',
        description: '系统自动生成民事起诉状',
        status: 'success'
      },
      {
        id: 5,
        time: '2024-01-15 16:05:00',
        type: 'generate',
        title: '生成证据清单',
        description: '系统自动生成证据清单',
        status: 'success'
      }
    ])

    // 计算属性
    const caseNumber = computed(() => route.params.caseNumber || caseInfo.value.caseNumber)

    // 方法
    const getFilingStatusType = (status) => {
      const types = {
        pending: 'info',
        processing: 'warning',
        completed: 'success',
        failed: 'danger'
      }
      return types[status] || 'info'
    }

    const getFilingStatusText = (status) => {
      const texts = {
        pending: '待处理',
        processing: '处理中',
        completed: '已完成',
        failed: '失败'
      }
      return texts[status] || '未知'
    }

    const getProgressColor = (percentage) => {
      if (percentage >= 100) return '#67C23A'
      if (percentage >= 80) return '#E6A23C'
      return '#F56C6C'
    }

    const getMaterialStatusType = (status) => {
      const types = {
        uploaded: 'success',
        missing: 'danger',
        processing: 'warning'
      }
      return types[status] || 'info'
    }

    const getMaterialStatusText = (status) => {
      const texts = {
        uploaded: '已上传',
        missing: '缺失',
        processing: '处理中'
      }
      return texts[status] || '未知'
    }

    const getDocumentIcon = (type) => {
      const icons = {
        complaint: 'fas fa-file-alt',
        evidenceList: 'fas fa-list',
        powerOfAttorney: 'fas fa-user-tie',
        identityDocuments: 'fas fa-id-card'
      }
      return icons[type] || 'fas fa-file'
    }

    const getTimelineItemType = (type) => {
      const types = {
        upload: 'primary',
        generate: 'success',
        submit: 'warning',
        complete: 'success'
      }
      return types[type] || 'info'
    }

    const getRecordStatusType = (status) => {
      const types = {
        success: 'success',
        pending: 'warning',
        failed: 'danger'
      }
      return types[status] || 'info'
    }

    const getRecordStatusText = (status) => {
      const texts = {
        success: '成功',
        pending: '处理中',
        failed: '失败'
      }
      return texts[status] || '未知'
    }

    const refreshData = async () => {
      loading.value = true
      try {
        // 模拟刷新数据
        await new Promise(resolve => setTimeout(resolve, 1000))
        ElMessage.success('数据刷新成功')
      } catch (error) {
        ElMessage.error('数据刷新失败')
      } finally {
        loading.value = false
      }
    }

    const uploadMaterial = () => {
      ElMessage.info('打开文件上传对话框')
    }

    const previewMaterial = (material) => {
      ElMessage.info(`预览材料：${material.name}`)
    }

    const downloadMaterial = (material) => {
      ElMessage.success(`下载材料：${material.name}`)
    }

    const deleteMaterial = async (material) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除材料"${material.name}"吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const index = materials.value.findIndex(m => m.id === material.id)
        if (index > -1) {
          materials.value.splice(index, 1)
          ElMessage.success('材料删除成功')
        }
      } catch {
        // 用户取消删除
      }
    }

    const generateDocument = async (doc) => {
      doc.generating = true
      
      try {
        await new Promise(resolve => setTimeout(resolve, 1500))
        doc.status = 'generated'
        ElMessage.success(`文书生成成功：${doc.name}`)
        
        // 添加生成记录
        filingRecords.value.push({
          id: filingRecords.value.length + 1,
          time: new Date().toLocaleString(),
          type: 'generate',
          title: `生成${doc.name}`,
          description: `系统自动生成${doc.name}`,
          status: 'success'
        })
      } catch (error) {
        ElMessage.error('文书生成失败，请重试')
      } finally {
        doc.generating = false
      }
    }

    const generateAllDocuments = async () => {
      generating.value = true
      
      try {
        for (const doc of documents.value) {
          if (doc.status !== 'generated') {
            await generateDocument(doc)
          }
        }
        ElMessage.success('所有文书生成完成')
      } catch (error) {
        ElMessage.error('批量生成失败')
      } finally {
        generating.value = false
      }
    }

    const downloadDocument = (doc) => {
      ElMessage.success(`下载文书：${doc.name}`)
    }

    const previewDocument = (doc) => {
      ElMessage.info(`预览文书：${doc.name}`)
    }

    onMounted(() => {
      // 根据路由参数加载案件数据
      console.log('加载案件详情：', caseNumber.value)
    })

    return {
      loading,
      generating,
      caseInfo,
      activeStep,
      materials,
      documents,
      filingRecords,
      caseNumber,
      getFilingStatusType,
      getFilingStatusText,
      getProgressColor,
      getMaterialStatusType,
      getMaterialStatusText,
      getDocumentIcon,
      getTimelineItemType,
      getRecordStatusType,
      getRecordStatusText,
      refreshData,
      uploadMaterial,
      previewMaterial,
      downloadMaterial,
      deleteMaterial,
      generateDocument,
      generateAllDocuments,
      downloadDocument,
      previewDocument
    }
  }
}
</script>

<style scoped>
.case-filing-detail {
  min-height: 100vh;
  background: #f5f7fa;
}

/* 自定义样式 */
.el-progress {
  margin-right: 8px;
}

.el-table .el-table__row:hover {
  background-color: #f5f7fa;
}

.el-timeline-item__content {
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .grid {
    grid-template-columns: 1fr;
  }
  
  .el-table {
    font-size: 12px;
  }
  
  .el-steps {
    font-size: 12px;
  }
}
</style>
